<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="题目标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入题目标题"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="queryParams.difficulty" placeholder="题目难度" clearable style="width: 200px">
            <el-option label="简单" value="EASY" />
            <el-option label="中等" value="MEDIUM" />
            <el-option label="困难" value="HARD" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="题目状态" clearable style="width: 200px">
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="草稿" value="DRAFT" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="Edit"
            :disabled="single"
            class="toolbar-button is-success"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 题目表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="problemList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="题目编号" align="center" prop="problemNumber" width="100" />
        <el-table-column label="题目标题" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="难度" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getDifficultyType(scope.row.difficulty)">
              {{ getDifficultyText(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="通过率" align="center" prop="passRate" width="100">
          <template #default="scope">
            {{ scope.row.passRate }}%
          </template>
        </el-table-column>
        <el-table-column label="提交数" align="center" prop="submitCount" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="PUBLISHED"
              inactive-value="DRAFT"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleTestCases" icon="List">测试用例</el-dropdown-item>
                    <el-dropdown-item command="handleSubmissions" icon="Document">提交记录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProblemPage, deleteProblem, updateProblemStatus, publishProblem, unpublishProblem } from '@/api/coding'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const problemList = ref([])
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  difficulty: undefined,
  status: undefined
})

// 获取题目列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getProblemPage(queryParams)
    if (response.code === 200) {
      problemList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取题目列表失败')
    }
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  router.push('/coding/problem/add')
}

// 修改按钮操作
const handleUpdate = (row) => {
  const problemId = row.id || ids.value[0]
  router.push(`/coding/problem/edit/${problemId}`)
}

// 删除按钮操作
const handleDelete = (row) => {
  const problemIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除题目编号为"' + problemIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProblem(problemIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除题目失败:', error)
      ElMessage.error('删除题目失败')
    }
  }).catch(() => {})
}

// 题目状态修改
const handleStatusChange = async (row) => {
  const text = row.status === 'PUBLISHED' ? '发布' : '下架'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.title + '"题目吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 根据状态调用不同的API
    if (row.status === 'PUBLISHED') {
      await publishProblem(row.id)
    } else {
      await unpublishProblem(row.id)
    }

    ElMessage.success(text + '成功')
    getList() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      row.status = row.status === 'PUBLISHED' ? 'DRAFT' : 'PUBLISHED'
      ElMessage.error(text + '失败')
    }
  }
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleTestCases':
      handleTestCases(row)
      break
    case 'handleSubmissions':
      handleSubmissions(row)
      break
    default:
      break
  }
}

// 测试用例管理
const handleTestCases = (row) => {
  router.push(`/coding/problem/${row.id}/testcases`)
}

// 提交记录
const handleSubmissions = (row) => {
  router.push(`/coding/problem/${row.id}/submissions`)
}

// 工具函数
const getDifficultyType = (difficulty) => {
  const typeMap = {
    'EASY': 'success',
    'MEDIUM': 'warning',
    'HARD': 'danger'
  }
  return typeMap[difficulty] || 'info'
}

const getDifficultyText = (difficulty) => {
  const textMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难'
  }
  return textMap[difficulty] || difficulty
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
